//
//  SearchViewController.m
//  Zyachting
//
//  Created by hungnt47 on 11/10/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SearchViewController.h"
#import "PriceRangeCell.h"
#import "ReferrenceCell.h"
#import "ButtonCell.h"
#import "JSON.h"
#import "Common.h"
#import "SearchResultController.h"
#import "NearbySeachController.h"
#import "CityTypeController.h"
@implementation SearchViewController
@synthesize table;
@synthesize contents;
@synthesize view1,picker;
@synthesize mode,selectedDict;
@synthesize pickerTitle;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"Search", @"Search");
        self.tabBarItem = [[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemSearch tag:0] autorelease];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [HUD setLabelText:@"Searching"];
    [self.view addSubview:HUD];
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"contents" ofType:@"plist"];
    self.contents = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
    self.selectedDict = [NSMutableDictionary dictionaryWithCapacity:2];
    [self.selectedDict setObject:[NSNumber numberWithInteger:0] forKey:@"category"];
    [self.selectedDict setObject:[NSNumber numberWithInteger:0] forKey:@"city"];
    [self.selectedDict setObject:[NSNumber numberWithInteger:0] forKey:@"bedroom"];
    [self.selectedDict setObject:[NSNumber numberWithInteger:0] forKey:@"bathroom"];   
//    UIBarButtonItem* right = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"StartSearchSmallV2.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(searchBtnTapped:)];
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"StartSearchSmallV3.png"] forState:UIControlStateNormal];
    [btn setFrame:CGRectMake(0, 0, 87, 29)];
    [btn addTarget:self action:@selector(searchBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* right = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = right;
    [right release];
    
    UIBarButtonItem* left = [[UIBarButtonItem alloc] initWithTitle:@"Search Nearby" style:UIBarButtonItemStyleBordered target:self action:@selector(nearbySearchTapped:)];
    self.navigationItem.leftBarButtonItem = left;
    [left release];
    [self.table setBackgroundView:nil];
    [self.table setBackgroundColor:[UIColor clearColor]];
//    [self generateContents];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark TableView DataSource Method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 7;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    switch (indexPath.section) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
            //normal
        {
            static NSString *CellIdentifier = @"Cell";
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            }
            switch (indexPath.section) {
                case 0:
                {
                    NSInteger index = [[self.selectedDict objectForKey:@"category"] integerValue];
                    cell.textLabel.text =  [[[self.contents objectForKey:@"category"] objectAtIndex:index] objectForKey:@"title"];
                    [cell setAccessoryType:UITableViewCellAccessoryNone];
                    cell.accessoryView = nil;
                }
                    break;
                case 1:
                {
                    NSInteger index = [[self.selectedDict objectForKey:@"city"] integerValue];
                    cell.textLabel.text =  [[self.contents objectForKey:@"cities"] objectAtIndex:index];
//                    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                    UIImage* image = [UIImage imageNamed:@"AssesoryBtn.png"];
                    CGRect frame = CGRectMake(0.0, 0.0, image.size.width/2, image.size.height/2);
                    button.frame = frame;
                    [button setBackgroundImage:image forState:UIControlStateNormal];
                    button.backgroundColor = [UIColor clearColor];
                    cell.accessoryView = button;
                }
                    break;   
                case 2:
                {
                    NSInteger index = [[self.selectedDict objectForKey:@"bedroom"] integerValue];
                    cell.textLabel.text = index == 0? @"Any":[NSString stringWithFormat:@"%d",index];
                    [cell setAccessoryType:UITableViewCellAccessoryNone];                    
                }

                    break; 
                case 3:
                {
                    NSInteger index = [[self.selectedDict objectForKey:@"bathroom"] integerValue];
                    cell.textLabel.text = index == 0? @"Any":[NSString stringWithFormat:@"%d",index];
                    [cell setAccessoryType:UITableViewCellAccessoryNone];                    
                }
                    break;
                case 4:
                {
                    NSInteger index = [[self.selectedDict objectForKey:@"PriceRange"] integerValue];
                    cell.textLabel.text = [[self.contents objectForKey:@"PriceRange"] objectAtIndex:index];
                    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                    UIImage* image = [UIImage imageNamed:@"AssesoryBtn.png"];
                    CGRect frame = CGRectMake(0.0, 0.0, image.size.width/2, image.size.height/2);
                    button.frame = frame;
                    [button setBackgroundImage:image forState:UIControlStateNormal];
                    button.backgroundColor = [UIColor clearColor];
                    cell.accessoryView = button;
                }
                    break;
                default:
                    break;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            return cell;
        }
            break;
//        case 4:
//            //
//        {
//            static NSString *PriceRangeCellIdentifier = @"PriceRangeCellIdentifier";
//            PriceRangeCell *cell = (PriceRangeCell *)[tableView
//                                                        dequeueReusableCellWithIdentifier: PriceRangeCellIdentifier];
//            if (cell == nil) {
//                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PriceRangeCell"
//                                                             owner:self options:nil];
//                for (id oneObject in nib)
//                    if ([oneObject isKindOfClass:[PriceRangeCell class]])
//                        cell = (PriceRangeCell *)oneObject;
//            }
//            [cell.tfMinimum setDelegate:self];
//            [cell.tfMaximum setDelegate:self];
//            tfMinimum =cell.tfMinimum;
//            tfMaximum = cell.tfMaximum;
//            [cell.tfMinimum addTarget:self action:@selector(textFieldEdittingDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
//            [cell.tfMaximum addTarget:self action:@selector(textFieldEdittingDone:) forControlEvents:UIControlEventEditingDidEndOnExit];  
//            cell.selectionStyle = UITableViewCellSelectionStyleNone;
//            return cell;
//        }
//            break;   
        case 5:
            //
        {
            static NSString *ReferrenceCellIdentifier = @"ReferrenceCellIdentifier";
            ReferrenceCell *cell = (ReferrenceCell *)[tableView
                                                      dequeueReusableCellWithIdentifier: ReferrenceCellIdentifier];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ReferrenceCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[ReferrenceCell class]])
                        cell = (ReferrenceCell *)oneObject;
            }
            tfReferrence = cell.tfReferrence;
            [cell.tfReferrence addTarget:self action:@selector(textFieldEdittingDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
            [cell.tfReferrence setDelegate:self];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;     
            [cell setBackgroundColor:[UIColor clearColor]];
            [cell setBackgroundView:nil];
            [cell.contentView setBackgroundColor:[UIColor clearColor]];
            return cell;
        }
            break;
        case 6:
        {
            static NSString *CellIdentifier1 = @"ButtonCellIdentifier";
            
            ButtonCell *cell = (ButtonCell *)[tableView
                                                      dequeueReusableCellWithIdentifier: CellIdentifier1];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ButtonCell"
                                                             owner:self options:nil];
                for (id oneObject in nib)
                    if ([oneObject isKindOfClass:[ButtonCell class]])
                        cell = (ButtonCell *)oneObject;
                [cell.contentView setBackgroundColor:[UIColor clearColor]];
                [cell setBackgroundView:nil];
                [cell setBackgroundColor:[UIColor clearColor]];
            }
            [cell.searchBtn addTarget:self action:@selector(searchBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
            [cell.resetBtn addTarget:self action:@selector(resetFilterBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView setBackgroundColor:[UIColor clearColor]];
            [cell setBackgroundView:nil];
            [cell setBackgroundColor:[UIColor clearColor]];
            return cell;
        }
        default:
            break;
    }
    return nil;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString* title = nil;
    switch (section) {
        case 0:
            //
            title = @"Type";
            break;
        case 1:
            //
            title = @"City";
            break;
        case 2:
            //
            title = @"Bedrooms";            
            break;
        case 3:
            //
            title = @"Bathrooms";                        
            break;
        case 4:
            //
            title = @"Price range";                                    
            break;
        case 5:
            //
            title = @"Search by referrence ID";
            break;
            
        default:
            break;
    }
    return title;
}
#pragma mark -
#pragma mark TableView Delegate Method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section<5 && indexPath.section !=1) {
        [self.table selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        self.mode = indexPath.section;
        [self showPickerWithMode:self.mode];
    }else if(indexPath.section == 1){
        CityTypeController* cityType = [[CityTypeController alloc] initWithNibName:@"CityTypeController" bundle:nil];
        NSInteger currentSelect = [[self.selectedDict objectForKey:@"city"] integerValue];
        [cityType setCurrenChooseType:currentSelect];
        [cityType setSearchViewController:self];
        UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:[cityType autorelease]];
        [nav.navigationBar setBarStyle:UIBarStyleBlackOpaque];
        [self.navigationController presentViewController:[nav autorelease] animated:YES completion:NULL];
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 6) {
        return 100.0f;
    }
    return 44;
}
#pragma mark -Helper
-(void)generateContents
{
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:kGET_CATEGORY]];
    [request setDelegate:self];
    [request setTag:0];
    [request startAsynchronous];

}
-(void)showPickerWithMode:(NSInteger)mode
{

    switch (self.mode) {
        case 0:
            [self.pickerTitle setText:@"Select Type"];
            break;
        case 1:
            [self.pickerTitle setText:@"Select City"];
            break;
        case 2:
            [self.pickerTitle setText:@"Select Bedroom"];
            break;
        case 3:
            [self.pickerTitle setText:@"Select Bathroom"];
            break;
        case 4:
            [self.pickerTitle setText:@"Select Price Range"];
            break;
        default:
            break;
    }
    [UIView animateWithDuration:0.3f animations:^{
        [self.view1 setFrame:CGRectMake(0, 151, 320, 216)];
        [self.table setFrame:CGRectMake(0, 0, 320, 151)];  
        [tfMaximum resignFirstResponder];
        [tfMinimum resignFirstResponder];
        [tfReferrence resignFirstResponder];
    }];
    [self.picker reloadAllComponents];
}

-(void)hidePicker
{
    [UIView animateWithDuration:0.3f animations:^{
        [self.view1 setFrame:CGRectMake(0, 367, 320, 216)];
        [self.table setFrame:CGRectMake(0, 0, 320, 367)];            
    }];
}
-(IBAction)cancelBtnTapped:(id)sender
{
    [self hidePicker];
}

-(IBAction)doneBtnTapped:(id)sender
{
    [self hidePicker];
}
-(IBAction)searchBtnTapped:(id)sender
{
//    [self.selectedDict setObject:[NSNumber numberWithInteger:0] forKey:@"category"];
//    [self.selectedDict setObject:[NSNumber numberWithInteger:0] forKey:@"city"];
//    [self.selectedDict setObject:[NSNumber numberWithInteger:0] forKey:@"bedroom"];
//    [self.selectedDict setObject:[NSNumber numberWithInteger:0] forKey:@"bathroom"]; 
    [HUD show:YES];
    NSInteger categoryIndex = [[self.selectedDict objectForKey:@"category"] integerValue];
    NSArray* category = [self.contents objectForKey:@"category"];
    NSDictionary* categoryDict = [category objectAtIndex:categoryIndex];
    NSInteger categoryID = [[categoryDict objectForKey:@"id"] integerValue];
    
    NSInteger cityIndex = [[self.selectedDict objectForKey:@"city"] integerValue];
    NSArray* cities = [self.contents objectForKey:@"cities"];
    NSString* cityName = [cities objectAtIndex:cityIndex];
    
    NSInteger bedRoom =  [[self.selectedDict objectForKey:@"bedroom"] integerValue];
    NSInteger bathroom = [[self.selectedDict objectForKey:@"bathroom"] integerValue];
    

    NSString* urlString = @"http://www.z-yachting.com/ws/search.php";
    urlString = [urlString stringByAppendingFormat:@"?type=%d",categoryID];
    if (![cityName isEqualToString:@"Any"]) {
        urlString = [urlString stringByAppendingFormat:@"&city=%@",cityName];
    }
    if (bedRoom!=0) {
        urlString = [urlString stringByAppendingFormat:@"&bedroom=%d",bedRoom];
    }
    if (bathroom) {
        urlString = [urlString stringByAppendingFormat:@"&bathroom=%d",bathroom];
    }
    
    NSInteger priceRange = [[self.selectedDict objectForKey:@"PriceRange"] integerValue];
    double min,max;
    min = 0.0f;
    max = 0.0f;
    switch (priceRange) {
        case 0:
        {
            min = 0.0f;
            max = 0.0f;
        }
            break;
        case 1:
        {
            min = 0;
            max = 100000.0f;
        }
            break;
        case 2:
        {
            min = 0;
            max = 200000.0f;
        }
            break;
        case 3:
        {
            min = 0;
            max = 300000.0f;
        }
            break;
        case 4:
        {
            min = 0;
            max = 500000.0f;
        }
            break;
        case 5:
        {
            max = 0;
            min = 500000.0f;
        }
            break;
        default:
            break;
    }
//    NSString* minPrice = tfMinimum.text;
//    NSString* maxPrice = tfMaximum.text;
//    if (![minPrice isEqualToString:@""]&& minPrice!=nil) {
//        double min = [minPrice doubleValue];
//        urlString = [urlString stringByAppendingFormat:@"&minprice=%f",min];
//    }
//    if (![maxPrice isEqualToString:@""]&& maxPrice!=nil) {
//        double max = [maxPrice doubleValue];
//        urlString = [urlString stringByAppendingFormat:@"&maxprice=%f",max];
//    }
    if (min>1) {
        urlString = [urlString stringByAppendingFormat:@"&minprice=%f",min];
    }
    if (max>1) {
        urlString = [urlString stringByAppendingFormat:@"&maxprice=%f",max];
    }
    NSString* referrence = tfReferrence.text;
    if (![referrence isEqualToString:@""]&& referrence!=nil) {
        urlString = [urlString stringByAppendingFormat:@"&reference=%@",referrence];
    }
    NSLog(urlString);
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString]];
    [request setDelegate:self];
    [request startAsynchronous];
}
-(IBAction)nearbySearchTapped:(id)sender
{
    NearbySeachController* nearbySearch = [[NearbySeachController alloc] initWithNibName:@"NearbySeachController" bundle:nil];
//    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:nearbySearch];
//    [nav.navigationBar setBarStyle:UIBarStyleBlackOpaque];
//    [self.tabBarController presentViewController:nav animated:YES completion:NULL];
//    [nav release];
    [self.navigationController pushViewController:nearbySearch animated:NO];
    [nearbySearch release];
}
-(IBAction)resetFilterBtnTapped:(id)sender
{
    
}
-(IBAction)textFieldEdittingDone:(id)sender
{
    [UIView animateWithDuration:0.3f animations:^{
        [self.table setFrame:CGRectMake(0, 0, 320, 367)];              
    }];
    [sender resignFirstResponder];
}
#pragma mark -UIPicker Datasource
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (self.mode) {
        case 0:
            //Type
        {
            NSArray* category = [self.contents objectForKey:@"category"];
            return category.count;
        }
            break;
        case 1:
            //City
        {
            NSArray* cities = [self.contents objectForKey:@"cities"];
            return cities.count;
        }
            break; 
        case 2:
            return 9;
            break;
        case 3:
            return 5;
            break;
        case 4:
        {
            NSArray* priceRange = [self.contents objectForKey:@"PriceRange"];
            return priceRange.count;
        }
            break;
        default:
            break;
    }
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString* title;
    switch (self.mode) {
        case 0:
            //Type
        {
            NSArray* category = [self.contents objectForKey:@"category"];
            title = [[category objectAtIndex:row] objectForKey:@"title"];
        }
            break;
        case 1:
            //City
        {
            NSArray* cities = [self.contents objectForKey:@"cities"];
            title = [cities objectAtIndex:row];
        }
            break; 
        case 2:
            if (row == 0) {
                title = @"Any";
            }else{
                title = [NSString stringWithFormat:@"%d",row];
            }
            break;
        case 3:
            if (row == 0) {
                title = @"Any";
            }else{
                title = [NSString stringWithFormat:@"%d",row];
            }            
            break;
        case 4:
        {
            title = [[self.contents objectForKey:@"PriceRange"] objectAtIndex:row];
        }
            break;
        default:
            break;
    }
    return title;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (self.mode) {
        case 0:
            [self.selectedDict setObject:[NSNumber numberWithInteger:row] forKey:@"category"];
            break;
        case 1:
            [self.selectedDict setObject:[NSNumber numberWithInteger:row] forKey:@"city"];
            break;
        case 2:
            [self.selectedDict setObject:[NSNumber numberWithInteger:row] forKey:@"bedroom"];
            break;
        case 3:
            [self.selectedDict setObject:[NSNumber numberWithInteger:row] forKey:@"bathroom"];
            break;
        case 4:
            [self.selectedDict setObject:[NSNumber numberWithInteger:row] forKey:@"PriceRange"];
            break;
        default:
            break;
    }
    [self.table reloadData];
}

#pragma mark -TextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3f animations:^{
        [self.view1 setFrame:CGRectMake(0, 367, 320, 216)];
        [self.table setFrame:CGRectMake(0, 0, 320, 200)];
        [self.table selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:4] animated:YES scrollPosition:UITableViewScrollPositionTop];
    }];
}
#pragma mark -ASIHTTPRequest Delegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    NSArray* resultArray = [request.responseString JSONValue];
    SearchResultController* searchResult = [[SearchResultController alloc] initWithNibName:@"SearchResultController" bundle:nil];
    [searchResult setItems:resultArray];
    [self.navigationController pushViewController:searchResult animated:YES];
    [searchResult release];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Connection Fail. Please try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}
@end
